/*
 * Copyright 2009 Lukasz Wozniak
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 *
 * http://www.apache.org/licenses/LICENSE-2.0 
 *
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 */
package pl.sind.factory;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.util.Map;
import java.util.Properties;

import pl.sind.http.HttpConnectorFactory;

/**
 * Base class for factories. Subclass implements methods providing defaults.
 * 
 * @author Lukasz Wozniak
 * 
 */
public abstract class AbstractFactory<P> {
	private static final Class<?>[] PROPS_PARAMS_ARRAY = new Class<?>[] { Properties.class };

	private final Class<P> TYPE;

	protected AbstractFactory(Class<P> type) {
		super();
		this.TYPE = type;
	}

	/**
	 * Uses default provided factory or the one configured in default property
	 * file.
	 * 
	 * @return instance of {@link HttpConnectorFactory}
	 */
	public P createFactory() {
		Properties props = new Properties();
		InputStream is = AbstractFactory.class.getClassLoader()
				.getResourceAsStream(getDefaultPropertiesFilename());
		if (is == null) {
			props.putAll(getDefaultProperties());
		} else {
			try {
				props.load(is);
			} catch (IOException e) {
				// shouldnt happen but if...
				throw new RuntimeException(
						"Fatal error reading factory configuration");
			}
		}
		return createFactory(props);

	}

	/**
	 * Uses provided properties to create factory.
	 * 
	 * @param props
	 *            properties configuring factory.
	 * @return instance of {@link P}
	 */
	@SuppressWarnings("unchecked")
	public P createFactory(Properties props) {
		String classname = props.getProperty(getFactoryClassProperty());
		if (classname != null) {
			try {
				Class<?> clazz = Class.forName(classname);
				if (TYPE.isAssignableFrom(clazz)) {
					try {
						Constructor<P> c = (Constructor<P>) clazz
								.getConstructor(PROPS_PARAMS_ARRAY);
						return (P) c.newInstance(new Object[] { props });
					} catch (Exception e) {
						// ignore doesn't matter
					}
					// fallback to default constructor
					return (P) clazz.newInstance();
				} else {
					throw new IllegalArgumentException(classname
							+ " does not implement " + TYPE.getName());
				}
			} catch (ClassNotFoundException e) {
				throw new IllegalArgumentException(e);
			} catch (InstantiationException e) {
				throw new RuntimeException(e);
			} catch (IllegalAccessException e) {
				throw new RuntimeException(e);
			}
		} else {
			throw new IllegalArgumentException(
					"Invalid factory configuration. "
							+ getDefaultPropertiesFilename());
		}
	}

	/**
	 * Provides classname of factory.
	 * 
	 * @return
	 */
	protected abstract String getFactoryClassProperty();

	/**
	 * Provides default property values.
	 * 
	 * @return
	 */
	protected abstract Map<? extends Object, ? extends Object> getDefaultProperties();

	/**
	 * Provides default properties filename to read from classpath.
	 * 
	 * @return
	 */
	protected abstract String getDefaultPropertiesFilename();

}
